package com.data.modules.base.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.data.common.api.dto.LogDTO;
import com.data.common.api.dto.SysDataLogDTO;
import com.data.common.entity.OperationDataChange;
import com.data.common.system.vo.LoginUser;
import com.data.common.util.CompareObjUtil;
import com.data.common.util.ConvertUtils;
import com.data.common.util.IPUtils;
import com.data.common.util.SpringContextUtils;
import com.data.modules.base.mapper.BaseCommonMapper;
import com.data.modules.base.service.BaseCommonService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class BaseCommonServiceImpl implements BaseCommonService {

    @Resource
    private BaseCommonMapper baseCommonMapper;

    @Override
    public void addLog(LogDTO logDTO) {
        if(ConvertUtils.isEmpty(logDTO.getId())){
            logDTO.setId(String.valueOf(IdWorker.getId()));
        }
        //保存日志（异常捕获处理，防止数据太大存储失败，导致业务失败）JT-238
        try {
            baseCommonMapper.saveLog(logDTO);
        } catch (Exception e) {
            log.warn(" LogContent length : "+logDTO.getLogContent().length());
            log.warn(e.getMessage());
        }
    }

    @Override
    public void addLog(String logContent, Integer logType, Integer operatetype, LoginUser user) {
        LogDTO sysLog = new LogDTO();
        sysLog.setId(String.valueOf(IdWorker.getId()));
        //注解上的描述,操作日志内容
        sysLog.setLogContent(logContent);
        sysLog.setLogType(logType);
        sysLog.setOperateType(operatetype);
        try {
            //获取request
            HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
            //设置IP地址
            sysLog.setIp(IPUtils.getIpAddr(request));
        } catch (Exception e) {
            sysLog.setIp("127.0.0.1");
        }
        //获取登录用户信息
        if(user==null){
            try {
                user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            } catch (Exception e) {
                //e.printStackTrace();
            }
        }
        if(user!=null){
            sysLog.setUserid(user.getUsername());
            sysLog.setUsername(user.getRealname());
        }
        sysLog.setCreateTime(new Date());
        //保存日志（异常捕获处理，防止数据太大存储失败，导致业务失败）JT-238
        try {
            baseCommonMapper.saveLog(sysLog);
        } catch (Exception e) {
            log.warn(" LogContent length : "+sysLog.getLogContent().length());
            log.warn(e.getMessage());
        }
    }

    @Override
    public void addLog(String logContent, Integer logType, Integer operateType) {
        addLog(logContent, logType, operateType, null);
    }

    /**
     * 异步 对比保存数据
     * @param list
     */
    @Async
    @Override
    public void compareAndTransfer(List<OperationDataChange> list) {
        if(list == null || list.size() == 0){
            return ;
        }

        list.stream().forEach( change->{
            List<?> oldData = change.getOldData();
            List<?> newData = change.getNewData();
            // 更新前后数据量不对必定是删除（逻辑删除）不做处理
            if (newData == null || oldData == null) {
                return;
            }
            if (oldData.size() != newData.size()) {
                return;
            }

            for (int i = 0; i < oldData.size(); i++) {
                try{
                    saveBizLogData(CompareObjUtil.converterDataAuditRecord(change,oldData.get(i),newData.get(i)));
                }catch (Exception e){
                }
            }

        });
    }

    private void saveBizLogData(SysDataLogDTO dto) {
        try{
            baseCommonMapper.saveBizLogData(dto);
        }catch (Exception e){
            log.warn(e.getMessage(),e);
        }
    }


}
